package com.jzqf.harmonydemo.ability;

import com.jzqf.harmonydemo.ability.slice.MainAbilitySlice;
import com.jzqf.harmonydemo.services.ServiceAbility;
import com.jzqf.harmonydemo.views.ListContainerAbility;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.bundle.IBundleManager;
import ohos.security.SystemPermission;

/**
 * Grid view
 */
public class MainAbility extends Ability {
    private final int PERMISSION_REQUEST_CODE = 101;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
        initPermission();
    }

    @Override
    protected void onActive() {
        super.onActive();
        //启动本地设备service
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName(ServiceAbility.class.getName())
                .build();
        intent.setOperation(operation);
        startAbility(intent);
//        //销毁service
//        stopAbility(intent);
    }

    private void initPermission() {
        if (verifySelfPermission(SystemPermission.CAMERA) != IBundleManager.PERMISSION_GRANTED) {
            //应用未被授权
            if (canRequestPermission(SystemPermission.CAMERA)) {
                //是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)
                requestPermissionsFromUser(new String[]{SystemPermission.CAMERA}, PERMISSION_REQUEST_CODE);
            } else {
                //显示应用需要权限的理由，提示用户进入设置授权
            }
        } else {
            //已授权
            startAbility();
        }
    }

    private void startAbility() {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withBundleName(getBundleName())
                .withAbilityName(ListContainerAbility.class.getName())
                .build();
        intent.setOperation(operation);
        startAbility(intent);
        terminateAbility();
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0
                    && grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
                // 权限被授予
                // 注意：因时间差导致接口权限检查时有无权限，所以对那些因无权限而抛异常的接口进行异常捕获处理
                startAbility();
            } else {
                // 权限被拒绝
                terminateAbility();
            }
        }
    }
}
